﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Light.Utility
{
    public interface ICache
    {
        void Add(string key, object value);
        object Get(string key);
        void Remove(string key);
        void Clear();
    }

    #region MemCache
    public class MemCache : ICache
    {
        private static Hashtable hashtable = new Hashtable();

        public MemCache()
        {
        }

        public void Add(string key, object value)
        {
            hashtable[key] = value;
        }

        public object Get(string key)
        {
            return hashtable[key];
        }

        public void Remove(string key)
        {
            hashtable.Remove(key);
        }

        public void Clear()
        {
            lock (hashtable)
            {
                hashtable.Clear();
            }
        }
    }
    #endregion

    #region SysCache
    public class SysCache : ICache, IEnumerable
    {
        private static HttpRuntime _httpRuntime = null;
        private TimeSpan _slidingExpiration = TimeSpan.Zero;

        public SysCache()
            : this(TimeSpan.FromSeconds(5 * 60))
        {
        }

        public SysCache(TimeSpan slidingExpiration)
        {
            this._slidingExpiration = slidingExpiration;
        }

        public void Add(string key, object value)
        {
            CacheItemRemovedCallback onRemove = null;

            if (webCache[key] == null)
            {
                webCache.Add(key, value, null, Cache.NoAbsoluteExpiration, _slidingExpiration, CacheItemPriority.Default, onRemove);
            }
            else
            {
                webCache.Insert(key, value, null, Cache.NoAbsoluteExpiration, _slidingExpiration, CacheItemPriority.Default, onRemove);
            }
        }

        public object Get(string key)
        {
            return webCache.Get(key);
        }

        public void Remove(string key)
        {
            webCache.Remove(key);
        }

        public void Clear()
        {
            HttpRuntime.Close();
        }

        private Cache webCache
        {
            get
            {
                if (_httpRuntime == null)
                {
                    lock (typeof(SysCache))
                    {
                        if (_httpRuntime == null)
                        {
                            _httpRuntime = new HttpRuntime();
                        }
                    }
                }

                return HttpRuntime.Cache;
            }
        }

        public IEnumerator GetEnumerator()
        {
            return webCache.GetEnumerator();
        }
    }
    #endregion
}
